import { group } from "console";
import { mongo } from "../mogoConfig";



const run = async () => {
    const memberTB = mongo.db("my_test").collection("members")

    const cursor1 = memberTB.aggregate([
        { $project: { _id: 1 } }
    ])

    console.log("聚合结果1-----------------------")
    for await (const item of cursor1) {
        console.log(JSON.stringify(item))
    }

    const cursor2 = memberTB.aggregate([
        {
            $project: { name: { $toUpper: "$_id" }, _id: 0 }
        },
        { $sort: { name: 1 } }
    ])

    console.log("聚合结果2-----------------------")
    for await (const item of cursor2) {
        console.log(JSON.stringify(item))
    }


    const cursor3 = memberTB.aggregate([
        {
            $project: {
                month_joined: { $month: "$joined" },
                name: "$_id",
                _id: 0
            }
        },
        {
            $sort: { month_joined: 1 }
        }
    ])

    console.log("聚合结果3-----------------------")
    for await (const item of cursor3) {
        console.log(JSON.stringify(item))
    }


    const cursor4 = memberTB.aggregate([
        {
            $project: {
                month_joined: { $month: "$joined" }
            }
        },
        {
            $group: {
                _id: { month_joined: "$month_joined" },
                number: { $sum: 1 }

            }
        },
        {
            $sort: { "_id.month_joined": 1 }
        }
    ])

    console.log("聚合结果4-----------------------")
    for await (const item of cursor4) {
        console.log(JSON.stringify(item))
    }

    const cursor5 = memberTB.aggregate([
        {
            $unwind: "$likes"
        },
        {
            $group: {
                _id: "$likes",
                number: { $sum: 1 }
            }
        },
        {
            $sort: { number: -1 }
        },
        {
            $limit: 5
        }
    ])

    console.log("聚合结果4-----------------------")
    for await (const item of cursor5) {
        console.log(JSON.stringify(item))
    }
}






run()
    .catch(error => {
        console.log(error)
    })
    .finally(() => {
        mongo.close()
        console.log("执行完成")
    })